﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

[RequireComponent(typeof(GUILayout.HorizontalScope))]
public class AreaPanelView : MonoBehaviour
{
    //绘制一份图

   [SerializeField] private AreaPanel areaPanel = new AreaPanel();
    
    private List<PanelView> _panelViews = new List<PanelView>(); 
    
    public float offsetX = 100;
    public float offestY = 100;
    
    
    public Vector2 rightLeft = new Vector2(0,0);//右上角


    private bool _Init;

    public void SetAreaPanel(AreaPanel areaPanel,MapEditorPanel mapEditorPanel,GameObject perfab)
    {
        this.areaPanel = areaPanel;
        this._mapEditorPanel = mapEditorPanel;
        this.perfab = perfab;
    }

    

    public void Delete()
    {
        _mapEditorPanel.RemoveAreaPanel(this);
    }
    
    
    /// <summary>
    /// 清理视图
    /// </summary>
    public void ClearView()
    {
        foreach (var panelView in _panelViews)
        {
            Destroy(panelView.gameObject);
        }
        _panelViews.Clear();
    }



    #region "数据读取"

   [SerializeField,Header("Temp")] private GameObject perfab;

   


    #region "数据设置"

    private Dictionary<string,PanelView> _dict =new Dictionary<string, PanelView>();
  [SerializeField]  private MapEditorPanel _mapEditorPanel;
    
    /// <summary>
    /// 获取 
    /// </summary>
    /// <param name="id"></param>
    /// <param name="areaPanelId"></param>
    /// <returns></returns>
    public PanelView TryToGetPanel(string id, string areaPanelId)
    {
        AreaPanelView areaPanelView = null;
        PanelView panelView = null;
        areaViewDic.TryGetValue(areaPanelId,out areaPanelView);
        
        if (areaPanelView == null)
        {
            Debug.LogError("未找到areaPanelId对象"+areaPanelId+"."+id);
        }
        else
        {
            _dict.TryGetValue(id, out panelView);
            if (panelView == null)
            {
                Debug.LogError("未找到id对象"+areaPanelId+"."+id);
            }
        }
        return panelView;
    }


    /// <summary>
    /// 创建面板对象
    /// </summary>
    /// <param name="areaPanel"></param>
    /// <param name="perfab"></param>
    public void CreatePanelView(GameObject perfab)
    {
        for (int i = 0; i < areaPanel.panelItems.Count; i++)
        {
            CreatePanelView(areaPanel.panelItems[i].id,areaPanel.panelItems[i], this.transform);
        }
    }

    public void UpdateInfo()
    {
        //更新布局
                LayOutGrid();
                
                //更新内容
                foreach (var panelView in _panelViews)
                {
                    panelView.OnValidate();
                    panelView.UpdateLayOut();
                }
                this.OnValidate();
    }
    


    public Dictionary<string, AreaPanelView> areaViewDic;

    /// <summary>
    /// 保存字典
    /// </summary>
    public void SetPanelViewDict(Dictionary<string, AreaPanelView> areaViewDic)
    {
        this.areaViewDic = areaViewDic;
        _dict.Clear();
        foreach (var view in _panelViews)
        {
            if (!_dict.ContainsKey(view.panelItem.id))
            {
                _dict.Add(view.panelItem.id, view);
            }
        }
    }
    
    //设置关系 2
    public void SetPanelViewRelation()
    {
        foreach (var panel in _panelViews)
        {
            panel.SetPanelViewRelation();
        }
        
    }

    #endregion


    private string prefix = "PanelItem";
    
    /// <summary>
    /// 创建PanelItem
    /// </summary>
    public void CreatPanelItem(GameObject perfab,Transform parent)
    {
        ClearView();
        this.perfab = perfab;
        for (int i = 0; i < areaPanel.panelItems.Count; i++)
        {
            _panelViews.Add(CreatePanelView(prefix,areaPanel.panelItems[i],parent));
        }
    }


    public int index = 0;
    
    /// <summary>
    /// 创建PanelView
    /// </summary>
    /// <param name="panelItem">数据</param>
    /// <param name="parent">父物体</param>
    /// <returns></returns>
    private PanelView CreatePanelView(string prefix, PanelItem panelItem,Transform parent)
    {
        GameObject go = Instantiate(perfab, parent);
        go.name = prefix;
        go.transform.localPosition= Vector3.zero;
        go.GetComponent<PanelView>().SetPanelItem(prefix, panelItem,this);
        return go.GetComponent<PanelView>();
    }
    
    /// <summary>
    /// 移除 Panel View
    /// </summary>
    /// <param name="panelView"></param>
    public void RemovePanelView(PanelView panelView)
    {
        if (_panelViews.Contains(panelView))
        {
            _panelViews.Remove(panelView);
            areaPanel.panelItems.Remove(panelView.panelItem);
        }
    }
    
    

    /// <summary>
    /// 添加面板
    /// </summary>
    public void AddPanelView()
    {
        PanelItem  panelItem = new PanelItem();
        panelItem.point = new Vector2(0,0);
        AddPanelView(CreatePanelView(prefix+"_"+index, panelItem,transform));
        index++;
    }
    
    #endregion
    
    


    /// <summary>
    /// 获取面板
    /// </summary>
    public AreaPanel GetAreaPanel
    {
        get
        {
            return this.areaPanel;
        }
    }

    void ClearAll()
    {
        areaPanel.panelItems.Clear();
        _panelViews.Clear();
    }
    
    /// <summary>
    /// 初始化
    /// </summary>
    public void Initialized()
    {
        ClearAll();
        foreach (var panelView in transform.GetComponentsInChildren<PanelView>())
        {
            AddPanelView(panelView);
            panelView.Initialized(panelView.panelItem.id);
        }
        name = areaPanel.Id;
        transform.localPosition = new Vector3(areaPanel.basePos.x,areaPanel.basePos.y,transform.localPosition.z);
        //transform.position = GetBasePoint;//更新位置
    }

    public void AddPanelView(PanelView panelView)
    {
        if (!_panelViews.Contains(panelView))
        {
            _panelViews.Add(panelView);
            areaPanel.panelItems.Add(panelView.panelItem);
            panelView.SetAreaPanelView(this);
        }
    }
    
    

    public void AutoCheak()
    {
        if(transform.childCount<=0) return;
        
        //数量不同步
        if (_panelViews.Count < transform.childCount)
        {
            foreach (var panelView in transform.GetComponentsInChildren<PanelView>())
            {
                AddPanelView(panelView);
            }
        }else if (_panelViews.Count > transform.childCount)
        {
            _panelViews.Clear();
            areaPanel.panelItems.Clear();
            foreach (var panelView in transform.GetComponentsInChildren<PanelView>())
            {
                AddPanelView(panelView);
            }
        }
    }
    
    
    

    public  void SetBasePos(Vector2 basePos, Vector2 column)
    {
        rightLeft.y = basePos.y + offestY * column.y;
        rightLeft.x = basePos.x + offsetX * column.x;

        LayOutGrid();
    }

    public List<PanelView> GetPanelItems
    {
        get
        {
            if (areaPanel.panelItems.Count < 0 || areaPanel.panelItems.Count < transform.childCount)
            {
                areaPanel.panelItems.Clear();
                PanelView panelItemTemp = null;
                for (int i = 0; i < transform.childCount; i++)
                {
                    panelItemTemp = transform.GetChild(i).GetComponent<PanelView>();
                    if (panelItemTemp)
                    {
                        areaPanel.panelItems.Add(panelItemTemp.panelItem);
                        _panelViews.Add((panelItemTemp));
                    }
                }
            }
            return _panelViews;
        }
    } 
    
    
    /// <summary>
    /// 布局
    /// </summary>
    public void LayOutGrid()
    {
        for (int i = 0; i < GetPanelItems.Count; i++)
        {
            GetPanelItems[i].transform.localPosition = GetRealPos(GetPanelItems[i].panelItem);
        }
    }


    
    public Vector2 PickPanelItemPoint(PanelView panel)
    {
        Vector2 pos = panel.transform.localPosition;
        //计算出当前的为
        float x = (pos.x )/offsetX +1;
        float y = (pos.y)/offestY +1;
        return  new Vector2((int)x,(int)y);
    }


    /// <summary>
    /// 获取真实位置
    /// </summary>
    /// <param name="panel"></param>
    /// <returns></returns>
    public Vector3 GetRealPos(PanelItem panel)
    {
        Vector2 pos = panel.point - Vector2.one*.5f;
        
        return GetBasePoint + new Vector3(pos.x *offsetX ,pos.y*offestY);
    }
    
    
    
    public Vector3 GetBasePoint
    {
        //get=>new Vector3(areaPanel.basePos.x,areaPanel.basePos.y,0);
        get =>Vector3.zero;
    }
    
    private void OnValidate()
    {
        if (!_Init)
        {
            Initialized();
            SetBasePos(new Vector2(0, 0), new Vector2(10,10));
            _Init = true;
        }

        if (_update)
        {
            _update = false;
            LayOutGrid();
        }
        //AutoCheak();
        name = areaPanel.Id;
        transform.localPosition = new Vector3(areaPanel.basePos.x,areaPanel.basePos.y,transform.localPosition.z);
    }

    private void OnDrawGizmosSelected()
    {
        areaPanel.basePos = transform.localPosition;
    }


    public bool _update;
    
    
    /// <summary>
    /// 绘制格子
    /// </summary>
    void DrawGrid()
    {
        Vector3 offset =new Vector2(offsetX,offestY);
        Vector3 startPos = transform.localPosition;//局部坐标
        Vector3 endPos;
        for (int i = 0; i < areaPanel.column.x+1; i++)
        {
            startPos = GetBasePoint + new Vector3(offsetX*i,0) - offset;
            endPos = startPos + new Vector3(0, offestY * areaPanel.column.y);
            //绘制横
            Gizmos.color = Color.blue;
            Gizmos.DrawLine(transform.TransformPoint(startPos),transform.TransformPoint(endPos));
        }

        for (int i = 0; i < areaPanel.column.y+1; i++)
        {
            startPos = GetBasePoint + new Vector3(0,offestY *i) -offset;
            endPos = startPos + new Vector3(offsetX*areaPanel.column.x, 0);
            
            
            //绘制横
            Gizmos.color = Color.blue;
            Gizmos.DrawLine(transform.TransformPoint(startPos),transform.TransformPoint(endPos));
        }
    }
    
    
    private void OnDrawGizmos()
    {
        //将位置绘制出来
        DrawGrid();
    }
    
    
}
